/*
	       File: HTTPGet.cs
	Create Date: 2007-12-1
	    Version:

	Description:


*/
using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Collections;
using System.Drawing;
using System.IO;
using System.Net;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Design;
using System.Workflow.ComponentModel.Compiler;
using System.Workflow.ComponentModel.Serialization;
using System.Workflow.Runtime;
using System.Workflow.Activities;
using System.Workflow.Activities.Rules;

using GuerillaProgrammer.Components;
using GuerillaProgrammer.Components.Logging;

namespace GuerillaProgrammer.FileProcessor.Activities
{
	public partial class HTTPGet: Activity
    {
        #region Private member fields
        private string _URL;
        private string _DownloadPath;
        #endregion

        #region Constructors and cleanup methods
        public HTTPGet()
        {
            InitializeComponent();
        }
        #endregion

        #region Private implementation methods
        private void WriteFile(Stream responseStream, string outputFileName)
        {
            BinaryWriter writer = new BinaryWriter(File.Create(outputFileName));
            int counter = 0;
            byte[] buffer = new byte[4096];
            do
            {
                counter = responseStream.Read(buffer, 0, buffer.Length);
                writer.Write(buffer, 0, counter);
            }
            while(counter != 0);
            writer.Flush();
            writer.Close();
        }
        #endregion

        #region Class properties
        public static DependencyProperty URLProperty = System.Workflow.ComponentModel.DependencyProperty.Register("URL", typeof(string), typeof(HTTPGet));
        [Description("URL of the file to be downloaded.")]
        [Category("HTTP GET")]
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public string URL
        {
            get { return _URL; }
            set { _URL = value; }
        }
        public static DependencyProperty DownloadPathProperty = System.Workflow.ComponentModel.DependencyProperty.Register("DownloadPath", typeof(string), typeof(HTTPGet));
        [Description("Path to put the downloaded file")]
        [Category("HTTP GET")]
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public string DownloadPath
        {
            get { return _DownloadPath; }
            set { _DownloadPath = value; }
        }
        #endregion

        #region Events handlers
        protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
        {
            try
            {
                Logger.LogEnter();

                IProcessorDataService dataService = executionContext.GetService(typeof(IProcessorDataService)) as IProcessorDataService;
                if (null == dataService)
                {
                    throw new InvalidOperationException("Can't get the service!");
                }

                WorkItem workItem = dataService.GetWorkItem();
                StringProcessor stringProcessor = new StringProcessor(new FileProcessorSymbolTable(dataService.GetConfiguration(), workItem));
                string url = stringProcessor.SubstituteStringValues(URL);
                string downloadPath = stringProcessor.SubstituteStringValues(DownloadPath);

                Logger.LogInfo("HTTPGet", "Getting: {0}\nDestination: {1}", url, downloadPath);
                WebRequest request = WebRequest.Create(url);
                request.Credentials = CredentialCache.DefaultCredentials;
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                //download binary data - have to decode
                Stream responseStream = response.GetResponseStream();
                WriteFile(responseStream, downloadPath);
                responseStream.Close();

                Logger.LogInfo("HTTPGet", "Download complete");

                response.Close();
                Logger.LogLeave();
                return base.Execute(executionContext);
            }
            catch (Exception exc)
            {
                Logger.LogError("HTTPGET ERROR", "An error occured in HTTPGet!\nError: {0}", exc.Message);
                Logger.LogLeave();

                return ActivityExecutionStatus.Faulting;
            }
        }
        #endregion
	}
}
